<?php

namespace WeForge\Console;

use Illuminate\Support\Str;
use Symfony\Component\Console\Input\ArgvInput as BaseArgvInput;

class ArgvInput extends BaseArgvInput
{
    /**
     * Create a new instance.
     */
    public function __construct()
    {
        $argv = collect($_SERVER['argv'])->reject(function ($argument) {
            return $this->ignore($argument);
        })->values()->all();

        parent::__construct($argv);
    }

    /**
     * @param  string $argument
     *
     * @return bool
     */
    protected function ignore($argument)
    {
        if ($ignored = Str::startsWith($argument, $start = '--weforge-context=')) {
            $this->handleContext(substr($argument, strlen($start)));
        }

        return $ignored;
    }

    /**
     * @param  string $context
     *
     * @return void
     */
    protected function handleContext($context)
    {
        $context = json_decode(base64_decode($context), true);

        foreach ($context['env'] ?? [] as $key => $value) {
            $_ENV[$key] = $value;
        }
    }
}
